/**
 * https://cloud.tencent.com/document/product/436/8629
 * node sdk 接入 腾讯COS
 */
import createFileHash from '@/utils/createFileHas';
import { getReadStreamLength } from '@/utils/fsPro';
import * as COS from 'cos-nodejs-sdk-v5';
import { ReadStream } from 'fs';
import { join } from 'path';

const TX_COS = new COS({
  SecretId: 'AKIDObZHkxuc7ML4XljRt52sVt1sTotiGYbO',
  SecretKey: 'auypSqzsWxA7pHTRAdqoX0DAsLYVCdom',
});

// 默认的上传图片的OSS桶
export const CommonImageBucket = {
  Bucket: 'common-iamge-1302770950' /* 桶 */,
  Region: 'ap-guangzhou' /* 桶所属地域 */,
};

export default {
  putImage: async (
    image: ReadStream | Buffer,
    options: {
      saveDir?: string;
      extname?: string;
    },
  ): Promise<string> => {
    const imageHash = await createFileHash(image);
    const Key = join(options.saveDir, imageHash + options.extname);

    await TX_COS.putObject({
      ...CommonImageBucket,
      Body: image,
      Key,
      ContentLength:
        image instanceof ReadStream
          ? await getReadStreamLength(image)
          : image.length,
    });

    return new Promise((resolve, reject) => {
      TX_COS.getObjectUrl(
        {
          ...CommonImageBucket,
          Key,
          Sign: false,
        },
        (err, data) => {
          if (err) reject(err);
          resolve(data.Url);
        },
      );
    });
  },
};
